<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-07-20
 * Time: 下午 2:25\
 * 短信接口
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use app\api\controller\Ecd;
class Send extends Controller{
      public function sendInfo(){
          $arr = input('param.');
          if(!$arr['mobile']){
              ajaxReturn(-1,'发送验证码手机号不能为空');
          }
          //检测发送的手机号是不是本站会员
          $isUser = Db::name('member')->where('member_mobile',$arr['mobile'])->find();
          if(empty($isUser)){
              ajaxReturn(-1,'该手机号不是本站会员');
          }
          $template = 1;
          $code = $this->getSendCode();
          $data = $this->getSendConfig();
          $ecd = new Ecd($data['url'],$data['app_key'],$data['app_secret'],$data['format']);
          $result = json_decode($ecd->send_sms_code($arr['mobile'],$template,$code,''),true);
          if($result['result'] == 0){
              $send_time  = time();
              $data['mobile'] = $arr['mobile'];
              $data['count'] = 1;
              $data['code'] = $code;
              $data['send_time'] = $send_time;
              $data['expre_time'] = $send_time+60*5;
              $this->sendCodeInsert($data);
              ajaxReturn(1,'发送成功');
          }else{
              ajaxReturn(1,'发送失败',$result);
          }
      }

    /**
     * @return mixed
     * 获取发送验证码配置
     */
    public function getSendConfig(){
        $data = Db::name('config')->where('type',1)->find();
        if(empty($data)){
            ajaxReturn(-1,'暂无发送手机验证码的配置信息');
        }
        return json_decode($data['content'],true);
    }
    /**
     * 获取验证码
     */
    public function getSendCode(){
        return rand(rand(1000,9999),rand(1000,9999));
    }
    /**
     * 存储发送的验证码
     */
    public function sendCodeInsert($data){
        $info = Db::name('send')->where('mobile',$data['mobile'])->find();
        if(empty($info)){
            //插入发送手机信息
            $res = Db::name('send')->insert($data);
        }else{
            $update['send_time'] = $data['send_time'];
            $update['expre_time'] = $data['expre_time'];
            $update['code'] = $data['code'];
            $update['count'] = $info['count']+$data['count'];
            $res = Db::name('send')->where('mobile',$data['mobile'])->update($update);
        }
        return $res;
    }
    /**
     * 检测验证码 是否过期以及正确
     */
    public function checkSendCode($mobile,$code){
        $info = Db::name('send')->where('mobile',$mobile)->find();
        if($info){
            $now = time();
            if($now>$info['expre_time']){
                ajaxReturn(-1,'验证码已过期');
            }
            if($info['code']!=$code){
                ajaxReturn(-1,'验证码错误');
            }
            return true;
        }else{
            return false;
        }
    }
}